package org.zju.demo.service.impl;

import org.zju.demo.model.Product;
import org.zju.demo.service.intf.ProductInfoIntf;
import org.zju.demo.utils.Constant;
import org.zju.demo.utils.HibernateUtil;

import java.util.List;

/**
 * Created by ZJDX on 2015/8/29.
 */
public class ProductInfoImpl implements ProductInfoIntf{
    public int updateProduct(Product product) {
        Product oldProduct = findByProductId(product.getProductId());
        if(oldProduct == null) {
            return Constant.UNKNOWN_PRODUCT;
        }
        HibernateUtil.update(product);
        return 0;
    }

    public List<Product> findByProductName(String name) {
        String hql = "from Product where productName=?";
        String[] parameters = {name};
        List<Product> list = HibernateUtil.executeQuery(hql, parameters);
        return list;
    }

    public List<Product> getAllProduct() {
        String hql = "from Product";
        List<Product> list = HibernateUtil.executeQuery(hql, null);
        return list;
    }

    public Product findByProductId(int productId) {
        String hql = "from Product where productId=?";
        String [] parameters = {Integer.toString(productId)};
        Product product = (Product)HibernateUtil.objectQuery(hql, parameters);
        return product;
    }

    public void addProduct(String productName, float price, int amount, String company) {
        Product product = new Product();
        product.setAmount(amount);
        product.setCompany(company);
        product.setProductName(productName);
        product.setPrice(price);

        HibernateUtil.saveIfNotExists(product);
    }

    public boolean addProduct(Product product) {
        HibernateUtil.saveOrUpdate(product);
        return true;
    }
}
